package com.inapp.ocreader;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;

import com.itwizard.mezzofanti.OCR;

public final class PreferencesActivity extends android.preference.PreferenceActivity implements OnSharedPreferenceChangeListener
    {
		private static final String TAG = "PreferencesActivity.java: ";
		private ProgressDialog m_ProgressDialog = null;							// local progress dialog for language download
		private DownloadManager m_DownloadManager = null;						// the download manager (for the langs)
		private SharedPreferences m_AppSharedPrefs = null;						// the application shared preferences, 

		public static final String KEY_USE_IMAGE_LIGHT_FILTER = "preferences_use_image_ligth_filter";
		public static final String KEY_SET_OCR_LANGUAGE = "preferences_set_OCR_language";
		public static final String KEY_DOWNLOAD_LANGUAGE = "preferences_download_language";
		
		// the options in the menu
		private CheckBoxPreference m_cbpUseImageLightFilter;
		private ListPreference m_lpSetOcrLanguage;
		private ListPreference m_lpDownloadLanguage;
		
	  @Override
	  protected void onCreate(Bundle icicle) 
	  {
		  try 
		  {
			    super.onCreate(icicle);
			    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
			    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			    addPreferencesFromResource(R.layout.preferences);
			
			    PreferenceScreen preferences = getPreferenceScreen();
			    m_AppSharedPrefs = preferences.getSharedPreferences();
			    preferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
			    m_cbpUseImageLightFilter = (CheckBoxPreference) preferences.findPreference(KEY_USE_IMAGE_LIGHT_FILTER);
			    m_lpSetOcrLanguage = (ListPreference) preferences.findPreference(KEY_SET_OCR_LANGUAGE);
			    m_lpDownloadLanguage = (ListPreference) preferences.findPreference(KEY_DOWNLOAD_LANGUAGE);
			    
				m_DownloadManager = new DownloadManager();
				m_DownloadManager.SetMessageHandler(m_LocalMessageHandler);
				CreateDownloadableLangsSubMenu();				
		
				CreateSettingsMenu();
		  }
		  catch (Exception ex)
		  {
			  Log.v(TAG, "exception: " + ex.toString());
		  }
	  }
	  
	  private void ShowAlert(String title, String message)
	  {
		  AlertDialog.Builder builder = new AlertDialog.Builder(this);
	      builder.setTitle(title);
	      builder.setMessage(message);
	      builder.setPositiveButton("Ok", null);
	      builder.show();							  
	  }
	      
    /**
     * create the settings menu
     */
    private void CreateSettingsMenu()
    {
	    try
	    {
		    // get settings from file and set it
	        m_cbpUseImageLightFilter.setChecked(OCR.mConfig.m_bUseBWFilter);

		    CreateValidLangsSubMenu();
    
	    }
	    catch (Exception ex)
	    {
	    	Log.v(TAG, "Exception: " + ex.toString());
	    }
    	
    }
    
    /**
     * Create the downloadable-languages submenu.
     */
    private void CreateDownloadableLangsSubMenu()
    {
		if (m_DownloadManager.DownloadLanguageBrief(OCReader.DOWNLOAD_URL, "languages.txt"))
		{
			// downloaded file correctly
			OCR.ReadAvailableLanguages();
			int len = m_DownloadManager.m_ServerLanguages.length;
		    CharSequence entriesLarge[] = new CharSequence[len];
		    CharSequence entries[] = new CharSequence[len];
		    for (int i=0; i<len; i++)
		    {
		    	if (OCR.mConfig.IsLanguageInstalled(m_DownloadManager.m_ServerLanguages[i].sExtName))
		    		entriesLarge[i] = m_DownloadManager.m_ServerLanguages[i].sFullName + " - " + (m_DownloadManager.m_ServerLanguages[i].lDownloadSz/1024) + "KB" + getString(R.string.preferencesactivity_reinstall);
		    	else
		    		entriesLarge[i] = m_DownloadManager.m_ServerLanguages[i].sFullName + " - " + (m_DownloadManager.m_ServerLanguages[i].lDownloadSz/1024) + "KB";
			    entries[i] = "" + i;
		    }		    
		    m_lpDownloadLanguage.setEntries(entriesLarge);
		    m_lpDownloadLanguage.setEntryValues(entries);
		    
		    m_lpDownloadLanguage.setOnPreferenceChangeListener(
		    	new OnPreferenceChangeListener() 
			    {
					//@Override
					public boolean onPreferenceChange(Preference preference, Object newValue) 
					{
						m_LocalMessageHandler.sendEmptyMessage(R.id.preferences_selectedLang2Download);
						return true;
					}
				}
		    );
		    
		}
		else
		{
		    CharSequence entriesLarge[] = new CharSequence[1];
		    entriesLarge[0] = getString(R.string.preferencesactivity_cannotaccessinternet);
		    m_lpDownloadLanguage.setEntries(entriesLarge);
		    m_lpDownloadLanguage.setEntryValues(entriesLarge);
			ShowAlert(getString(R.string.preferencesactivity_warning), getString(R.string.preferencesactivity_problems));
		}    	
    }

    /**
     * Create the available-languages submenu.
     */
    private void CreateValidLangsSubMenu()
    {
    	OCR.ReadAvailableLanguages();
	    String[] svLangs = OCR.mConfig.GetvLanguages();
	    m_lpSetOcrLanguage.setEntries(svLangs);
	    m_lpSetOcrLanguage.setEntryValues(OCR.mConfig.m_asLanguages);
	    m_lpSetOcrLanguage.setValue(OCR.mConfig.GetLanguage());
    	
    }

	/**
	 * the local message handler
	 */
	private Handler m_LocalMessageHandler = new Handler() 
	{
		
		@Override
		public void handleMessage(Message msg) 
		{
			switch(msg.what)
			{
				// download manager started unziping
				case R.id.downloadmanager_unziping:
					m_ProgressDialog.setMessage(getString(R.string.preferencesactivity_pd_body2));					
					break;
					
				// download manager finished with an error
				case R.id.downloadmanager_downloadFinishedError:
					m_ProgressDialog.dismiss();
					ShowAlert(getString(R.string.preferencesactivity_download_title), getString(R.string.preferencesactivity_downloaderr_body));
					break;
					
				// download manager finished with an error
				case R.id.downloadmanager_downloadFinishedErrorSdcard:
					m_ProgressDialog.dismiss();
					ShowAlert(getString(R.string.preferencesactivity_download_title), getString(R.string.preferencesactivity_downloaderrsdcard_body));
					break;
					
				// download manager finished ok 
				case R.id.downloadmanager_downloadFinishedOK:
					m_ProgressDialog.dismiss();
					CreateValidLangsSubMenu();
					CreateDownloadableLangsSubMenu();
					ShowAlert(getString(R.string.preferencesactivity_download_title), getString(R.string.preferencesactivity_downloadok_body));
					int index = Integer.parseInt(m_lpDownloadLanguage.getValue());
					String lang = m_DownloadManager.m_ServerLanguages[index].sExtName;
					Log.v(TAG, "Installed " + lang);
					//OCR.get().SetLanguage(lang);
					
					// save lang in file
			    	SharedPreferences.Editor spe = m_AppSharedPrefs.edit();
		        	spe.putString(KEY_SET_OCR_LANGUAGE, lang);
			    	spe.commit();    	
					
					Log.v(TAG, "mconfig lang=" + OCR.mConfig.GetLanguageMore());
					break;
					
				// user selected a language to download
				case R.id.preferences_selectedLang2Download:
					m_DownloadManager.DownloadLanguageJob(Integer.parseInt(m_lpDownloadLanguage.getValue()));
					CreateProgressDialog(m_lpDownloadLanguage.getEntry());			    	
					m_DownloadManager.SetProgressDialog(m_ProgressDialog);
					break;
			}
		}
	};

	
	/**
	 * create a progress dialog for the download menu
	 * @param lang the language that is downloaded
	 */
	private void CreateProgressDialog(CharSequence lang)
	{
		
		m_ProgressDialog = new ProgressDialog(this);
		m_ProgressDialog.setTitle(R.string.preferencesactivity_pd_title);
		m_ProgressDialog.setMessage(getString(R.string.preferencesactivity_pd_body1) + " " + lang);
		m_ProgressDialog.setCancelable(true);
		m_ProgressDialog.setMax(100);
		m_ProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		m_ProgressDialog.show();
		
		m_ProgressDialog.setOnCancelListener(new OnCancelListener() {
    		public void onCancel(DialogInterface dialog) 
    		{
    			m_DownloadManager.CancelDownload();    			
	        }    		    		
    	});		
	}
	
	//@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
	{		
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if ( keyCode == KeyEvent.KEYCODE_BACK )
        { 	// if "BACK-KEY" pressed
            if (event.getRepeatCount() == 0)
            {
            	finish();
            }
        }
        
        return super.onKeyDown(keyCode, event);
    }
}
